"use strict";

const Controller = require("egg").Controller;

/**
 * @controller 分类CRUD
 */
class CategoryController extends Controller {
  /**
   * @summary 查询所有分类
   * @router get /api/category
   * @apikey
   */
  async index() {
    const { ctx } = this;
    ctx.body = {
      code: 200,
      msg: "查询所有分类",
      data: await ctx.model.Category.findAll(),
    };
  }

  /**
   * @summary 分类详情
   * @router get /api/category/{id}
   * @request path number id 分类Id
   * @apikey
   */
  async show() {
    const { ctx } = this;
    const id = ctx.params.id;
    ctx.body = {
      code: 200,
      msg: ` id=${id}分类详情`,
      data: await ctx.model.Category.findByPk(id),
    };
  }

  /**
   * @summary 创建分类
   * @router post /api/category
   * @request body CategoryBody 分类Body
   * @apikey
   */
  async create() {
    const { ctx } = this;
    const category = ctx.request.body;
    ctx.body = {
      code: 200,
      msg: "创建分类",
      data: await ctx.model.Category.create(category),
    };
  }

  /**
   * @summary 更新分类提交
   * @router put /api/category/{id}
   * @request path number id 分类Id
   * @request body CategoryBody 分类Body
   * @apikey
   */
  async update() {
    const { ctx } = this;
    const category = ctx.request.body;
    const id = ctx.params.id;
    const res = await ctx.service.category.update(category, id);
    ctx.body = {
      code: 200,
      msg: "更新分类",
      data: "操作数量:" + res,
    };
  }

  /**
   * @summary 刪除分类
   * @router delete /api/category/{id}
   * @request path number id 分类Id
   * @apikey
   */
  async destroy() {
    const { ctx } = this;
    const categoryId = ctx.params.id;
    const res = await ctx.service.category.destroy(categoryId);
    ctx.body = {
      code: 200,
      msg: "删除分类",
      data: "操作数量:" + res,
    };
  }
}

module.exports = CategoryController;
